<?php

namespace app\admin\service\user;

use app\admin\service\ExportService;
use app\api\service\ApiTokenService;
use app\common\enum\ChannelEnum;
use app\common\model\user\User;
use tmcore\base\BaseService;
use tmcore\services\CacheService;
use app\common\service\UserService as SysUserService;
use tmcore\services\JwtTokenService;

class UserService extends BaseService
{
    /**
     * 获取列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '=' => ['status', 'group_id','mobile','id',],
            '%like%' => ['nickname','account'],
            'datetime' => ['create_time'],
        ];
        $where = self::getSearchData($searchParam);

        // 返回分页数据
        $list = User::page($where, self::getPageData(),'*', ['id' => 'desc'], ['group_name', 'status_desc']);

        foreach ($list['list'] as &$item) {
            $item['avatar'] =  get_file_url($item['avatar']);
        }

        return $list;
    }

    /**
     * 添加用户
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        self::beginTrans();
        try{
            (new SysUserService)->register([
                'account' => $params['account'],
                'password' => $params['password'],
                'channel' => ChannelEnum::PC,
                'group_id' => $params['group_id'],
                'mobile' => $params['mobile'],
                'nickname' => $params['nickname'],
                'real_name' => $params['real_name'],
                'birthday' => $params['birthday'],
                'id_card' => $params['id_card'],
                'avatar' => $params['avatar'],
                'sex' => $params['sex'],
                'email' => $params['email'],
                'status' => $params['status'],
                'admin_id' => $params['admin_id'],
            ]);
            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 编辑用户
     * @param array $params
     * @return bool
     */
    public static function edit(array $params) : bool
    {
        $data = [
            'mobile' => $params['mobile'],
            'group_id' => $params['group_id'],
            'nickname' => $params['nickname'],
            'real_name' => $params['real_name'],
            'birthday' => $params['birthday'],
            'id_card' => $params['id_card'],
            'avatar' => $params['avatar'],
            'sex' => $params['sex'],
            'email' => $params['email'],
            'status' => $params['status'],
            'admin_id' => $params['admin_id'],
        ];
        if(!empty($params['password'])) $data['password'] = User::getPassword($params['password'], 'user_register');

        return User::edit($data, $params['id']);
    }


    /**
     * 查看用户详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        $user = User::where(['id' => $params['id']])
            ->hidden(['password'])
            ->append(['group_name', 'status_desc','channel_ids','channel_names','last_time_desc'])
            ->findOrEmpty();
        if ($user->isEmpty()) return [];
        $user = $user->toArray();

        $user['avatar'] =  get_file_url($user['avatar']);
        return $user;
    }

    /**
     * 查看用户token信息
     * @param $params
     * @return array
     */
    public static function tokenInfo($params) : array
    {
        if (!User::where(['id' => $params['id']])->count()) return [];

        $cache_key = "api_token_" . $params['id'];
        $cache_token_list = CacheService::get($cache_key);

        $data = [];
        if(is_array($cache_token_list) && count($cache_token_list) > 0) {
            foreach ($cache_token_list as $value) {
                try{
                    $res = JwtTokenService::parseToken($value[0], false);
                    array_unshift($data, [
                        'channel_name' => ChannelEnum::getChannelDesc($res['params']['channel']),
                        'create_time' => date('Y-m-d H:i:s', $res['params']['iat']),
                        'expire_time' => date('Y-m-d H:i:s', $res['params']['exp']),
                        'token' => $value[0]
                    ]);
                } catch (\Exception $e) {
                    continue;
                }
            }
        }

        return $data;
    }

    /**
     * 删除用户token
     * @param $params
     * @return bool
     */
    public static function deleteToken($params) {
        return ApiTokenService::clearToken($params['id'], $params['token']);
    }

    /**
     * 更改用户状态
     * @param array $params
     * @return bool
     */
    public static function updateStatus(array $params)
    {
        return User::edit([
            'status' => $params['status']
        ], $params['id']);
    }


    /**
     * 导出会员列表
     * @param array $params
     * @param array $adminInfo
     * @return array|bool
     */
    public static function export(array $params, array $adminInfo)
    {
        $searchParam = [
            '=' => ['status', 'group_id','mobile','id',],
            '%like%' => ['nickename'],
            'datetime' => ['create_time'],
        ];
        $where = self::getSearchData($searchParam,[],$params);

        $export_params = self::getExportData($params);
        $list = User::exportPage($export_params,$where, self::getPageData(),"id,account,nickname,group_id,real_name,birthday,id_card,sex,mobile,email,status,create_time", ['id' => 'desc'],['group_name', 'status_desc','sex_desc']);

        $filename = '用户列表';
        $header = [
            'id' => 'ID',
            'account' => '账号',
            'nickname' => '昵称',
            'real_name' => '真实姓名',
            'group_name' => '分组名称',
            'birthday' => '生日',
            'id_card' => '身份证号',
            'sex_desc' => '性别',
            'mobile' => '手机号',
            'email' => '邮箱',
            'status_desc' => '状态',
            'create_time' => '创建时间',
        ];
        $res = ExportService::exportExcel($list,$filename,$header,['name' => $adminInfo['name']]);
        if($res === false) {
            return self::setError(ExportService::getError());
        } else {
            return $res;
        }
    }
}